package com.tutucms.service.admin.common;

import com.tutucms.common.util.JsonUtil;
import com.tutucms.service.auth.UserContextCache;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import net.sf.ehcache.config.CacheConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * Created by wangxudong on 2020/10/28.
 * <p> <p>没有redis时的替代方案</p>
 * 自定义的我的用户数据缓存,这里我们使用ehcache作为本地存储
 * ，如果用户接入并配置了redis，则删除本类默认使用redis缓存来存储
 *
 * @version: 1.0
 * @modified :
 * @see com.tutucms.service.auth.impl.DefaultUserContextCache
 * @see com.tutucms.service.configuration.UserContextCacheConfig
 */
@Component
public class MyUserContentCache implements UserContextCache {

    @Autowired(required = false)
    private CacheManager cacheManager;

    @Value("${app.token.timeout:4320}")
    private Long tokenTimeout;

    @Override
    public void set(String key, Object value, long expire) {

        getCache().put(new Element(key, JsonUtil.toJson(value)));
    }

    @Override
    public <T> T get(String key, Class<T> clazz) {

        Element element = getCache().get(key);

        return element == null ? null : JsonUtil.fromJson(element.getObjectValue().toString(), clazz);
    }

    @Override
    public <T> T get(String key, Class<T> clazz, long expire) {

        Element element = getCache().get(key);

        return element == null ? null : JsonUtil.fromJson(element.getObjectValue().toString(), clazz);
    }

    @Override
    public void delete(String key) {

        getCache().remove(key);
    }

    private Cache getCache() {

        if (cacheManager == null) {
            cacheManager = CacheManager.create();
        }
        Cache cache = cacheManager.getCache("users");
        if (cache == null) {
            CacheConfiguration cacheConfiguration = new CacheConfiguration();
            cacheConfiguration.setName("users");
            cacheConfiguration.setTimeToIdleSeconds(tokenTimeout);
            cacheConfiguration.setEternal(false);
            // 最大内存消耗1GB
            cacheConfiguration.setMaxBytesLocalHeap(1073741824L);
            cacheManager.addCache(new Cache(cacheConfiguration));
        }

        return cacheManager.getCache("users");
    }

}
